package com.ys168.gam.searcher;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys168.gam.bean.EngineInfo;
import com.ys168.gam.bean.SearchConditionInfo;

/**
 * 谷歌搜索，需要对获取的数据进行编码UTF-8
 * 
 * @author Jason Krebs
 * @since 2015年6月9日
 */
public class GoogleSearcher extends BaseSearcher {

    public GoogleSearcher(EngineInfo engineInfo, SearchConditionInfo searchConditionInfo) {
        super(engineInfo, searchConditionInfo);
    }

    @Override
    protected List<URL> parse(String data) throws Exception {
        List<URL> urls = new ArrayList<URL>();

        JSONObject object = JSONObject.parseObject(new String(data.getBytes(), "UTF-8"));
        JSONObject responseData = object.getJSONObject("responseData");
        if (object.getIntValue("responseStatus") != 200 || responseData == null) {
            throw new Exception("responseStatus:" + object.getIntValue("responseStatus"));
        }
        JSONArray dataArray = responseData.getJSONArray("results");

        for (int i = 0; i < dataArray.size(); i++) {
            JSONObject obj = dataArray.getJSONObject(i);

            String imageUrl = obj.getString("unescapedUrl");
            if (imageUrl == null || imageUrl.isEmpty()) {
                continue;
            }
            urls.add(new URL(imageUrl));
        }

        return urls;
    }
}
